package cn.lg.soar.flow.api.model.node;

import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.flow.api.enums.NodeStatusEnum;
import cn.lg.soar.flow.api.utils.XmlUtils;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Data
public class ExclusiveGateway implements Node, Serializable {

    private String key;
    private NodeStatusEnum status;
    private List<ExclusiveGatewayItem> items;


    @JsonProperty("type")
    @Override
    public String getType() { return "exclusive-gateway"; }

    @Override
    public String getName() {
        return "Exclusive Gateway"; // 可选：可以增加 name 字段
    }
    public void setName(String name) {
        // 如果需要可修改，可添加字段
    }

    @Override
    public String getDescription() {
        return "An exclusive gateway for conditional routing.";
        // 或者添加 description 字段
    }
    public void setDescription(String description) {
        // 同上
    }

    @Override
    public String inKey() {
        return key + "_in";
    }

    @Override
    public String outKey() {
        return key + "_out";
    }

    public String toXmlString() {
        String name = XmlUtils.escapeXml(getName());
        String splitKey = inKey();   // 分支网关 ID
        String joinKey = outKey();   // 合并网关 ID
        String defaultFlowId = key + "_default"; // 默认分支id
        StringBuilder sb = new StringBuilder();
        // 添加注释（可选，不影响解析）
        sb.append("<!-- Exclusive Gateway: ").append(getName()).append(" -->\n");
        // 分支网关（split）
        sb.append("<exclusiveGateway id=\"").append(splitKey)
                .append("\" name=\"").append(name)
                .append("\" default=\"").append(defaultFlowId).append("\" />\n");
        // 分支处理
        for (int i = 0; i < items.size(); i++) {
            ExclusiveGatewayItem item = items.get(i);
            List<Node> nodes = item.getNodes();
            String branchId = key + "_branch_" + i;
            String condition = item.getCondition(); // 假设有此方法
            boolean isDefault = Boolean.TRUE.equals(item.getIsDefault());
            List<ProcessListener> processListeners = item.getProcessListeners();

            String currentSource = splitKey;
            // 如果有子节点，生成整个分支链
            if (DataUtil.isValuable(nodes)) {
                for (int j = 0; j < nodes.size(); j++) {
                    Node node = nodes.get(j);
                    String flowId = branchId + "_flow_" + j;

                    if (j == 0) {
                        // 生成 sequenceFlow（带条件）
                        sb.append("<sequenceFlow id=\"").append(isDefault ? defaultFlowId : flowId)
                                .append("\" sourceRef=\"").append(currentSource)
                                .append("\" targetRef=\"").append(node.inKey()).append("\">\n");
                        if (condition != null && !condition.isEmpty()) {
                            sb.append("  <conditionExpression xsi:type=\"tFormalExpression\">")
                                    .append("<![CDATA[").append(condition).append("]]></conditionExpression>\n");
                        }
                        // 添加执行监听器
                        if (DataUtil.isValuable(processListeners)) {
                            sb.append("<extensionElements>");
                            if (DataUtil.isValuable(processListeners)) {
                                for (ProcessListener x : processListeners) {
                                    sb.append("<flowable:executionListener event=\"take\" ")
                                            .append(Boolean.TRUE.equals(x.getIsExpression()) ? "expression" : "class")
                                            .append("=\"").append(XmlUtils.escapeXml(x.getValue())).append("\" />\n");
                                }
                            }
                            sb.append("</extensionElements>\n");
                        }
                        sb.append("</sequenceFlow>\n");
                    } else {
                        // 生成 sequenceFlow（无条件）
                        sb.append("<sequenceFlow id=\"").append(flowId)
                                .append("\" sourceRef=\"").append(currentSource)
                                .append("\" targetRef=\"").append(node.inKey()).append("\" />\n");

                    }

                    // 生成节点 XML
                    sb.append(node.toXmlString());

                    currentSource = node.outKey();
                }

                // 节点连接线
                String exitFlowId = branchId + "_exit";
                sb.append("<sequenceFlow id=\"").append(exitFlowId)
                        .append("\" sourceRef=\"").append(currentSource)
                        .append("\" targetRef=\"").append(joinKey).append("\" />\n");

            } else {
                // 无子节点，直接连接
                sb.append("<sequenceFlow id=\"").append(isDefault ? defaultFlowId : (branchId + "_flow_0"))
                        .append("\" sourceRef=\"").append(splitKey)
                        .append("\" targetRef=\"").append(joinKey).append("\">\n");
                if (condition != null && !condition.isEmpty()) {
                    sb.append("  <conditionExpression xsi:type=\"tFormalExpression\">")
                            .append("<![CDATA[").append(condition).append("]]></conditionExpression>\n");
                }
                sb.append("</sequenceFlow>\n");
            }
        }

        // 合并网关（join）
        sb.append("<exclusiveGateway id=\"").append(joinKey)
                .append("\" name=\"").append(name).append(" - Join\" />\n");

        return sb.toString();
    }

}